// 定义（或者获取）商品数据
const productData = [
  {
    id: 1001,
    imgUrl: "./imgs/apple.png",
    title: "苹果",
    titleEn: "Apple",
    price: 2.99,
  },
  {
    id: 1002,
    imgUrl: "./imgs/beer.png",
    title: "啤酒",
    titleEn: "Beer",
    price: 14.99,
  },
  {
    id: 1003,
    imgUrl: "./imgs/milk.png",
    title: "牛奶",
    titleEn: "Milk",
    price: 4.99,
  },
  {
    id: 1004,
    imgUrl: "./imgs/doughnut.png",
    title: "甜甜圈",
    titleEn: "Doughnut",
    price: 19.99,
  },
  {
    id: 1005,
    imgUrl: "./imgs/bread.png",
    title: "面包",
    titleEn: "Bread",
    price: 3.99,
  },
  {
    id: 1006,
    imgUrl: "./imgs/aubergine.png",
    title: "茄子",
    titleEn: "Aubergine",
    price: 3.49,
  },
  {
    id: 1007,
    imgUrl: "./imgs/lettuce.png",
    title: "生菜",
    titleEn: "Lettuce",
    price: 2.99,
  },
  {
    id: 1008,
    imgUrl: "./imgs/flour.png",
    title: "谷物",
    titleEn: "Flour",
    price: 17.99,
  },
];

let productList = document.querySelector("#product-list");
let cartList = document.querySelector("#cart-list");
let totalPrice = document.querySelector(".total .price");

// 生成商品列表
productData.forEach((product) => {
  /* productList.insertAdjacentHTML(
    "beforeend",
    `
        <li>
            <img src="${product.imgUrl}" alt="">
            <h4>${product.title}</h4>
            <h5>${product.titleEn}</h5>
            <h6>¥${product.price}</h6>
            <button prod-id='${product.id}'>加入购物车</button>
        </li>
    `
  ); */

  let li = document.createElement("li");
  li.innerHTML = `
      <img src="${product.imgUrl}" alt="">
      <h4>${product.title}</h4>
      <h5>${product.titleEn}</h5>
      <h6>¥${product.price}</h6>
      <button>加入购物车</button>
  `;
  li.prod = product; // 将商品对象关联给li对象
  productList.appendChild(li);
});

// 从cookie中取数据
let cookieData = getCookie("cartData");
const cartData = cookieData ? JSON.parse(cookieData) : [];

// 生成购物车列表
cartData.forEach((product) => {
  // console.log(product);
  insertLiToCart(product);
});

calcTotalPrice();



// 利用事件委托将加入购物车按钮的点击事件绑定给product-list
productList.addEventListener(
  "click",
  (e) => {
    let target = e.target; //得到事件源
    if (target.tagName === "BUTTON") {
      /* 
        // 以下代码是通过自定义dom属性保存product的id，然后再从productData数组中找到对应的id的product对象
        // 这种思路比较常见，也比较容易理解，是大多数人应该掌握的方式
        let productId = target.getAttribute("prod-id");
        let product = productData.find(element => {
            return element.id == productId;
        }); 
        */

      let product = target.parentNode.prod;
      product.quantity = product.quantity || 1; // 购买数量

      let productFromCart = cartData.find((element) => {
        return element.id == product.id;
      });

      // 判断cartData中是否包含当前product
      if (productFromCart) {
        // 如果有
        // 改变cartList中对应的quantity输入框中的值
        productFromCart.quantity++;
        // let quantityInput = document.getElementById(product.id);
        let quantityInput =
          productFromCart.dom.querySelector(".quantity-input");
        quantityInput.value = productFromCart.quantity;
      } else {
        // 如果没有
        // product.quantity = 1; // 购买数量
        insertLiToCart(product);
        cartData.push(product);

        // 存入cookie
        setCookie("cartData", JSON.stringify(cartData));
      }
    }
  },
  false
);

// 向cartList中插入li
function insertLiToCart(product) {
  let li = document.createElement("li");
  li.innerHTML = `
    <div class="item">
        <img src="${product.imgUrl}" alt="">
        <p>${product.title}</p>
    </div>
    <div class="price">
        <p>¥${product.price}</p>
    </div>
    <div class="quantity">
        <input type="number" id="${product.id}" class="quantity-input" value="${product.quantity}">
    </div>
    <div class="delete">
        <button>X</button>
    </div>
  `;
  cartList.appendChild(li);
  product.dom = li; // 将li关联给product
  // li.product = product; // 将product关联给li
}

// quantity输入框的input事件
cartList.addEventListener(
  "input",
  (e) => {
    let target = e.target;
    if (target.className == "quantity-input") {
      cartData.map((product) => {
        if (product.id == target.id) {
          product.quantity = target.value;
        }
      });
      setCookie("cartData", JSON.stringify(cartData));
      calcTotalPrice();
    }
  },
  false
);

function calcTotalPrice() {
  let result = 0;
  // 生成购物车列表
  cartData.forEach((product) => {
    result += product.price * product.quantity;
  });

  totalPrice.innerHTML = "$" + result;
}

// test----------------------------------------------------------------
// cartData1 = [
//   {
//       "id": 1002,
//       "imgUrl": "./imgs/beer.png",
//       "title": "啤酒",
//       "titleEn": "Beer",
//       "price": 14.99,
//       "quantity": 1
//   },
//   {
//       "id": 1003,
//       "imgUrl": "./imgs/milk.png",
//       "title": "牛奶",
//       "titleEn": "Milk",
//       "price": 4.99,
//       "quantity": 1
//   }
// ];

// let prod1 = {
//   "id": 1002,
//   "imgUrl": "./imgs/beer.png",
//   "title": "啤酒",
//   "titleEn": "Beer",
//   "price": 14.99,
//   "quantity": 1
// }

// console.log(cartData1.includes( cartData1[0] ));
